import time
from telnetlib import EC

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

from common.Util import BlogDriver

class BlogEdit:
    driver = ""
    url = ""

    def __init__(self):
        self.driver = BlogDriver.driver
        # 博客编辑页面
        self.url = "http://8.137.19.140:9090/blog_edit.html"
        self.driver.get(self.url)

    def BlogLoginEditTest(self):
        # 先检测元素
        # 标题输入框
        self.driver.find_element(By.CSS_SELECTOR, "#title")
        # 工具栏（这里工具栏中的工具是第三方插件，元素无法被选中，不进行详细检测）
        self.driver.find_element(By.CSS_SELECTOR,"#editor > div.editormd-toolbar > div > ul")
        # 正文编写框
        self.driver.find_element(By.CSS_SELECTOR,"#editor > div.CodeMirror.cm-s-default.CodeMirror-wrap > div.CodeMirror-scroll > div.CodeMirror-sizer > div > div > div > div.CodeMirror-code > div > pre > span > span")
        # 正文展示框
        self.driver.find_element(By.CSS_SELECTOR,"#editor > div.editormd-preview")
        # 发布按钮
        self.driver.find_element(By.CSS_SELECTOR,"#submit")
        # 通过发布一篇博客来进行测试
        # 先测试失败发布博客
        # 只填标题、只填正文、两者都不填
        # 由于正文内容的编辑采用的是第三方插件，这里也无法进行清空或编写操作，所以只能测试没有标题的情况
        self.driver.find_element(By.CSS_SELECTOR,"#title").clear()
        self.driver.find_element(By.CSS_SELECTOR,"#submit").click()
        # wait = WebDriverWait(self.driver, 5)
        # # 检查弹窗是否出现
        # wait.until(EC.alert_is_present())
        # 找到弹窗
        time.sleep(2)
        alert = self.driver.switch_to.alert
        # 判断一下弹窗里面的内容？
        actual = alert.text
        print(actual)
        alert.accept()  # 接受弹窗
        # 再测试成功发布博客
        self.driver.find_element(By.CSS_SELECTOR,"#title").send_keys("自动化测试发布文章")
        self.driver.find_element(By.CSS_SELECTOR,"#submit").click()
        time.sleep(2)# 发布文章后，会自动跳转到博客列表页，可以判断一下跳转后的url是否等于博客列表页的url
        jumpURL = self.driver.current_url
        jumptitle = self.driver.title
        print(jumpURL)
        assert jumpURL == "http://8.137.19.140:9090/blog_list.html"
        assert jumptitle == "博客列表页"
        # 判断一下博客列表页的文章标题是否是新发布的博客的给定的标题
        # body > div.container > div.right > div: nth - child(4) > div.title
        # 最近发布一篇文章是child（4）新发布的文章应该是child（5）
        time.sleep(1)
        actual = self.driver.find_element(By.CSS_SELECTOR,"body > div.container > div.right > div:nth-child(5) > div.title").text
        print(actual)
        assert actual == "自动化测试发布文章"
        self.driver.quit()
